<template>
  <view class="wrapper">
    <u-navbar
      :title="title"
      @leftClick="leftClick(urlIndex)"
      bgColor="#F6F6F6"
      titleStyle="font-weight: 500; color: #000000;"
      :placeholder="true"
    >
      <view
        class="u-nav-slot"
        :class="{ 'u-nav__active': isCanNext }"
        slot="right"
        @click="nextHandle"
      >
        {{ nextBtn }}
      </view>
    </u-navbar>

    <!-- 选择人数 -->
    <view class="select-number">
      {{ alreadySelectList.length + newSelectList.length }}/{{ userList.length }}
    </view>

    <!-- 搜索框 -->
    <view class="search-content">
      <u-input
        :placeholder="$t('index.Search')"
        v-model="searchValue"
        placeholderClass="placeholderClass"
        border="none"
        inputAlign="center"
        shape="circle"
        :customStyle="{
          background: '#fff',
          height: '76rpx',
          padding: '0 38rpx',
          'font-size': '26rpx',
        }"
      ></u-input>
      <view
        class="iconfont icon-sousuo serch-icon"
        v-show="!searchValue"
      ></view>
    </view>

    <!-- 已选择用户头像以及未选择用户时提示语区域 -->
    <view class="tip-content" v-if="newSelectList.length > 0">
      <scroll-view scroll-x="true" class="scroll-X">
        <view
          class="avatar"
          :class="'avatar' + index"
          v-for="(item, index) in newSelectList"
          :key="index"
        >
          <image
            v-if="isPeopleAvatarExit(item.userVo.avatarCompress || item.userVo.avatar)"
            :src="item.userVo.avatarCompress || item.userVo.avatar"
            class="avatar-image"
            mode="aspectFill"
          >
          </image>
          <view
            v-else
            class="avatar-image avator-font-setting"
            :style="{ background: `${getDefaultColor(item.userVo.avatarColorCode)}`, fontSize: '30upx', fontWeight: '400' }"
            >{{ formatUserName(item).slice(0, 1) }}</view
          >
        </view>
      </scroll-view>
    </view>

    <view class="tip-content tip-content-text" v-else>
      <view class="tip-content__text">
        {{ tipText }}
      </view>
    </view>

    <u-checkbox-group id="scroll-Y-id">
      <scroll-view
        scroll-top="0"
        scroll-y="true"
        class="scroll-Y"
        :scroll-into-view="scrollIntoView"
      >
        <view class="chat-content">
          <view v-for="(item, index) in list" :key="index">
            <view class="pinyin-line" :id="'s-' + (item.initial === '#' ? '0' : item.initial)">{{
              item.initial
            }}</view>

            <view
              v-for="(item1, index1) in item.data"
              :key="index1"
              class="chat-line"
            >
              <view
                class="chat-line__item"
                @click.stop="changeStateHandle(item1)"
              >
                <u-checkbox
                  :checked="item1.isSelect"
                  :disabled="item1.isDisabled || isSingleSelect && newSelectList.length === 1 && newSelectList[0].id !== item1.id"
                  shape="circle"
                  activeColor="#61BDB2"
                  :name="item1.id"
                  @change="changeStateHandle(item1)"
                >
                </u-checkbox>
                <image
                  v-if="isPeopleAvatarExit(item1.userVo.avatarCompress || item1.userVo.avatar)"
                  :src="item1.userVo.avatarCompress || item1.userVo.avatar"
                  class="avatar-image"
                  mode="aspectFill"
                >
                </image>
                <view
                  v-else
                  class="avatar-image avator-font-setting"
                  :style="{ background: `${getDefaultColor(item1.userVo.avatarColorCode)}`, fontSize: '30upx', fontWeight: '400' }"
                  >{{ formatUserName(item1).slice(0, 1) }}</view
                >
                <text class="right-text omit">{{ formatUserName(item1) }}</text>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </u-checkbox-group>
    <view class="suspension-frame" v-if="list && list.length > 0">
      <view
        class="text"
        v-for="(item, index) in list"
        :key="index"
        @click="onLocation(item.initial)"
				:class="{ active: currentView == item.initial }"
        >{{ item.initial }}</view
      >
    </view>
  </view>
</template>

<script>
import { mapMutations } from "vuex";
import { inviteGroup } from "@/services/group";
import { getGroupMemberList, getDefaultColor } from "@/utils/index";
import { addBlockUser } from "@/services/user";

export default {
  data() {
    return {
      searchValue: "",
      newSelectList: [],
      type: "",
      tipText: "",
      userList: [],
      title: "",
      groupId: "",
      nextBtn: "",
      currentView: "",
      scrollIntoView: "",
			isSingleSelect: false,
      otherParams: {},
      alreadySelectList: [],
			urlIndex: 'selectFriend',
    };
  },
  computed: {
    // 能否执行下一步
    isCanNext() {
      return this.newSelectList.length > 0 ? true : false;
    },
    list() {
      if (!this.searchValue) {
        let arr = this.pySegSort(this.userList);
				this.currentView = arr && arr.length > 0 ? arr[0].initial : '';
				return arr
      } else {
        let arr = this.pySegSort(
          this.userList.filter((item) => {
            return (
             ( item.formatUserName.match(this.searchValue) ||
              String(item.userVo.userId).match(this.searchValue)) && !item.userVo?.isOppositeBlockUser
            );
          })
        );
				this.currentView = arr && arr.length > 0 ? arr[0].initial : '';
				return arr
      }
    },
  },
  watch: {
    "$store.state.selectFriendOption": {
      handler: function (newVal, oldVal) {
        let data = JSON.parse(JSON.stringify(newVal));
				this.isSingleSelect = data?.isSingle || false
        data?.UserList?.forEach((item) => {
          this.$set(item, "isSelect", false);
          data.defaultIdList?.forEach((item1) => {
            if (
              item1.userVo &&
              item.userVo &&
              item1.userVo.userId == item.userVo.userId
            ) {
              // item.nickName = item1.nickName || '';
              item.isSelect = true;
              item.isDisabled = true;
              this.alreadySelectList.push(item)
              // this.$set(item, 'isDisabled', true);
            }
          });
        });
        let newList = data.UserList || [];
        newList.map((item) => {
          item.formatUserName = this.formatUserName(item);
          return item;
        }).filter((o) => o.userVo != null)
        // 1 创建群聊 2 添加成员 需要去除黑名单人员
        if (Number(data.type) === 1 || Number(data.type) === 2) {
          newList.filter((o) => !o.isBlockUser)
        }
        this.userList = newList;
        this.defaultIdList = data.defaultIdList || [];
        this.type = data.type;
        this.tipText = data.tipText;
        this.title = data.title;
        this.nextBtn = data.nextBtn || this.$t("index.Next");
        this.otherParams = data?.otherParams || {}
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    getDefaultColor,
    ...mapMutations(["SET_SUBMIT_FRIEND_LIST"]),
    onLocation(value) {
      console.log(value);
      this.scrollIntoView = "s-" + (value === '#' ? '0' : value);
      this.currentView = value;
      console.log(value);
    },
    // 点击next执行回调
    nextHandle() {
      this.SET_SUBMIT_FRIEND_LIST(this.newSelectList);
      console.log("next!!!", this.newSelectList, this.type);
      // 1 创建群聊 2 添加成员 3 添加黑名单 4 分享名片
      switch (this.type) {
        case 1: //创建群聊
          uni.redirectTo({
            url: "/pages/selectFriend/CreateGroup",
          });
          break;
        case 2: //添加成员
          this.addMembers();
          break;
        case 3: //	添加黑名单
          // console.log('添加黑名单在此操作')
          this.addBlackUser();
          break;
				case 4: // 分享名片
					this.onShareCard();
					break
        default:
          break;
      }
    },
    // 添加成员
    async addMembers() {
      var resp = await inviteGroup({
        groupId: this.groupId,
        userIds: this.newSelectList.map((t) => {
          return t.friendId;
        }),
      });
      if (!resp.success) return;
      // getGroupMemberList(this.groupId);
      setTimeout(() => {
        uni.navigateBack();
      }, 500);
    },
    // 改变选中状态回调
    changeStateHandle(val) {
			console.log(val);
      if (val.isDisabled) return;
      val.isSelect = !val.isSelect;
      if (val.isSelect) {
        this.newSelectList.push(val);
      } else {
        this.newSelectList = this.newSelectList.filter((item) => {
          return val.id !== item.id;
        });
      }
    },
    async addBlackUser() {
      const resp = await addBlockUser({
        blockUserIdList: this.newSelectList.map((t) => {
          return t.friendId;
        }),
      });
      if (!resp.success) return;
      uni.showToast({
        title: this.$t("index.add-success"),
        icon: "none",
        duration: 1500,
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 900);
    },
		// 分享名片功能
    onShareCard () {
      const timestamp = new Date().getTime()
      // 定义消息投送目标会话
      const conversation = this.otherParams
      // 配置属性
      const options = {
        messageId: timestamp
      }

      const info = {
        ...this.newSelectList[0].userVo,
        commentName: this.newSelectList[0].commentName,
        commentLast: this.newSelectList[0].commentLast
      }
      
      const message = new this.$RongIMLib.CardMessage({
        content: '',
        info: info
      })

      this.sendMessage(conversation, message, options)
    },
    async sendMessage (conversation, message, options) {
      console.log(conversation, message, options)
      // 发送消息
      const res = await this.$RongIMLib.sendMessage(
        conversation,
        message,
        options
      )

      if (res.code === this.$RongIMLib.ErrorCode.SUCCESS) {
        this.$store.dispatch("upChatList", res.data);
        uni.navigateBack({
          delta: 1
        })
      }
    },
  },
  onLoad(option) {
    this.groupId = option.groupId;
		this.getPrePages(this.urlIndex)
  },
};
</script>

<style lang="scss" scoped>
.omit {
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  word-wrap: break-word;
  white-space: pre-wrap;
  word-break: break-word;
}
.wrapper {
  box-sizing: border-box;
  font-family: Source Han Sans CN;

  .u-nav-slot {
    font-size: 28rpx;
    font-weight: bold;
    color: #000000;
    opacity: 0.3;
    pointer-events: none;
  }

  .u-nav__active {
    pointer-events: all;
    color: #61bdb2;
    opacity: 1;
  }

  .select-number {
    text-align: center;
    font-size: 26rpx;
    color: #878787;
  }

  .search-content {
    position: relative;
    width: 690rpx;
    height: 76rpx;
    margin: 0 auto;
    margin-top: 24rpx;

    /deep/ .placeholderClass {
      font-size: 26rpx;
      font-family: Source Han Sans CN;
      font-weight: 400;
      color: #878787 !important;
      margin-left: 24rpx;
    }

    .serch-icon {
      position: absolute;
      top: 50%;
      left: 277rpx;
      color: #878787;
      font-size: 30rpx;
      transform: translateY(-50%);
    }
  }

  .tip-content-text {
    text-align: center;
    padding: 0 !important;
    line-height: 136rpx;
  }

  .tip-content {
    height: 136rpx;
    box-sizing: border-box;
    padding: 40rpx 30rpx 16rpx;

    &__text {
      font-size: 28rpx;
      color: #61bdb2;
    }

    .scroll-X {
      height: 100%;
      white-space: nowrap;

      .avatar {
        display: inline-block;
        margin-left: 30rpx;
        height: 100%;
      }

      .avatar0 {
        margin-left: 0;
      }
    }
  }

  .suspension-frame {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    right: 20upx;
    width: 40upx;
    background: rgba($color: #000000, $alpha: 0.4);
    border-radius: 20upx;
    box-sizing: border-box;
    padding: 12upx 0;
    text-align: center;

    .text {
      font-size: 22upx;
      font-weight: 400;
      color: #ffffff;
      margin: 6upx 0;

      &.active {
        margin: 6rpx auto;
        width: 34upx;
        // height: 34upx;
        background: #61bdb2;
        border-radius: 17upx;
      }
    }
  }
  .scroll-Y {
    height: calc(100vh - 44px - 280rpx - var(--status-bar-height));
  }

  .chat-content {
    background-color: #f6f6f6;

    .chat-line {
      background-color: #fff;
      padding: 0 30rpx;
      border-bottom: 2rpx solid #f6f6f6;

      &__item {
        height: 120rpx;
        display: flex;
        flex-direction: row;
        align-items: center;
      }

      .avatar-image {
        margin: 0 30rpx;
      }
      .right-text {
        flex: 1;
        font-size: 30upx;
        font-weight: 400;
        color: #000000;
      }
    }
  }

  .avatar-image {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    text-align: center;
    line-height: 80rpx;
    font-size: 30upx;
    font-weight: 400;
    color: #ffffff;
  }

  .pinyin-line {
    width: 100%;
    height: 66upx;
    box-sizing: border-box;
    padding: 0 30upx;
    font-size: 24upx;
    font-weight: 400;
    color: #878787;
    line-height: 66upx;
    background: #f6f6f6;
  }
}
/deep/.scroll-X .uni-scroll-view-content {
  display: flex;
  align-items: center;
}
</style>
